<template>
  <div>
    <div class="Information">
      <div>
        <Button
          class="informationBtn"
          type="primary"
          ghost
          @click="modal11 = true"
          >ADALAB 查看所有面试信息</Button
        >
        <Modal
          v-model="modal11"
          :footer-hide="true"
          fullscreen
          title="ADALAB所有面试信息"
        >
          <div class="xinXiBotton">
            <div>
              <Button @click="handleSelectAll(true)" type="success"
                >全部选择</Button
              >
              <Button @click="handleSelectAll(false)" type="success"
                >全部取消</Button
              >
              <Button type="success" ghost
                >已选中{{ selection.length }}个选项</Button
              >
            </div>

            <div>
              <Poptip
                confirm
                title="确定要删除吗？"
                @on-ok="PostDel"
                @on-cancel="ok"
              >
                <Button type="error">删除已选择</Button>
              </Poptip>
            </div>
          </div>

          <div class="xinXiBotton">
            <div>
              <Button type="primary" size="large" @click="exportData()">
                导出为 Excel
              </Button>
              <Button @click="setsortBy()" type="primary">{{
                this.sortBy
              }}</Button>
            </div>
          </div>

          <div>
            <Table
              highlight-row
              @on-selection-change="SelectInformation"
              border
              ref="selection"
              :columns="columns4"
              :data="data1"
              height="500"
            ></Table>
          </div>
        </Modal>
      </div>

      <div>
        <Button @click="modal12 = true" type="primary" ghost>添加用户</Button>
        <Modal footer-hide v-model="modal12" fullscreen title="添加用户">
          <div id="addUserCont">
            <Form
              id="addUser"
              ref="formInline"
              :model="formInline"
              :rules="ruleInline"
              inline
            >
              <FormItem prop="user">
                <Input
                  class="addUserInput"
                  type="text"
                  v-model="formInline.user"
                  placeholder="用户名"
                >
                  <Icon type="ios-person-outline" slot="prepend"></Icon>
                </Input>
              </FormItem>
              <FormItem prop="password">
                <Input
                  type="password"
                  v-model="formInline.password"
                  placeholder="密码"
                  @on-enter="handleSubmit('formInline')"
                >
                  <Icon type="ios-lock-outline" slot="prepend"></Icon>
                </Input>
              </FormItem>
              <FormItem>
                <Button type="primary" @click="handleSubmit('formInline')"
                  >添加</Button
                >
              </FormItem>
            </Form>
          </div>
        </Modal>
      </div>
    </div>

    <div id="bodyDiv">
      <form id="adminApp">
        <div class="modal" v-show="data.isShowInterviewer">
          <div class="modal-cont">
            <span class="close-btn" @click="deselect">&times;</span>
            <div class="modal-cont-title">
              <h4>选择一位面试官</h4>
            </div>

            <div class="userList">
              <a
                v-for="(item, index) in data.user"
                :key="index"
                class="userName"
                @click="selectInterviewer"
                >{{ item }}</a
              >
            </div>
          </div>
        </div>
        <div class="modal" v-show="data.isShowInterviewee">
          <div class="modal-cont">
            <span class="close-btn" @click="deselect">&times;</span>
            <div class="modal-cont-title">
              <h4>选择一位求职者</h4>
            </div>

            <div class="userList">
              <a
                v-for="(item, index) in data.user"
                :key="index"
                class="userName"
                @click="selectInterviewee"
                >{{ item }}</a
              >
            </div>
          </div>
        </div>
        <div id="adminSelectUser">
          <div>
            <p class="moduleDescription">选择面试官</p>
            <button type="button" class="selectUser" @click="openInterviewer">
              {{ data.interviewerMsg }}
            </button>
          </div>
          <div>
            <p class="moduleDescription">选择求职者</p>
            <button type="button" class="selectUser" @click="openInterviewee">
              {{ data.intervieweeMsg }}
            </button>
          </div>
        </div>

        <div id="selectTime">
          <p class="moduleDescription">选择时间</p>
          <DatePicker
            v-model="data.time"
            type="datetime"
            placeholder="选择日期与时间"
            style="width: 200px"
            :time-picker-options="{ steps: [1, 10, 10] }"
          ></DatePicker>
        </div>

        <div id="interviewContent">
          <p class="moduleDescription">选择文档</p>
          <div id="files">
            <input
              name="myFile"
              type="file"
              class="seles_wenDang"
              @change="getFiles($event)"
            />
          </div>
        </div>

        <div id="release">
          <input
            type="submit"
            value="发布任务"
            id="releaseButton"
            @click.prevent="publishTask"
          />
        </div>
      </form>
      <!--      点击发布后的加载动图-->
      <Spin size="large" fix v-if="spinShow"></Spin>
    </div>
  </div>
</template>

<script>
export default {
  name: "AdminInterface",
  created: function () {
    this.getUserName();
    this.getInformation();
  },

  data() {
    return {
      spinShow: false,
      sortBy: "Wonderland AI 排序",
      formInline: {
        user: "",
        password: "",
      },

      ruleInline: {
        user: [{ required: true, message: "请输入用户名", trigger: "blur" }],

        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            type: "string",
            min: 6,
            message: "密码长度不能小于6位",
            trigger: "blur",
          },
        ],
      },

      modal12: false,

      num: "",

      selection: {
        length: 0, // 选中的总条数
        ids: [], // 所有被选择行的id
      },

      modal11: false,

      columns4: [
        {
          type: "selection",
          width: 60,
          align: "center",
          resizable: true,
        },

        {
          title: "面试官",
          key: "Interviewer",
          resizable: true,
          width: 90,
        },
        {
          title: "面试官反馈",
          key: "Interviewer_Feedback",
          resizable: true,
          // width: 180,
        },

        {
          title: "求职者",
          key: "JobSeekers",
          resizable: true,
          width: 90,
        },
        {
          title: "求职者反馈",
          key: "JobSeekers_Feedback",
          resizable: true,
          // width: 180,
        },

        {
          title: "面试时间",
          key: "InterviewTime",
          resizable: true,
          width: 190,
        },

        {
          title: "录音",
          key: "action",
          width: 150,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "large",
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.DownloadRecording(params.index);
                    },
                  },
                },
                "下载录音"
              ),
            ]);
          },
          resizable: true,
          width: 180,
        },
        {
          title: "PDF",
          key: "action",
          width: 150,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "large",
                  },
                  on: {
                    click: () => {
                      this.DownloadPDF(params.index);
                    },
                  },
                },
                "下载PDF文档"
              ),
            ]);
          },
          resizable: true,
          width: 180,
        },
        {
          title: "面试状态",
          key: "Status",
          resizable: true,
          width: 110,
        },
      ],

      data1: [],
      data: {
        isShowInterviewee: false,
        isShowInterviewer: false,
        user: [],
        interviewee: "",
        interviewer: "",
        intervieweeMsg: "点击选择",
        interviewerMsg: "点击选择",
        time: "",
        data_3: null,
      },
      filename: null,
    };
  },

  methods: {
    // 监听文档
    getFiles(e) {
      this.filename = e.target.files;
      console.log(e.target.files);
    },
    // 确定是否要删除
    ok() {
      this.$Message.info("取消删除");
    },
    // 下载pdf
    DownloadPDF(index) {
      let interviewId = this.data1[index]["id"];
      // console.log("面试id" + this.data1[index]["id"]);
      this.$Spin.show();
      fetch("/api/interviewer/pdf/" + interviewId)
        .then((res) => {
          if (res.status === 200) {
            return res.json();
          }
          throw new Error("Error");
        })
        .then((json) => {
          let b64 = atob(json["key"]);
          let n = b64.length;
          let arr = new Uint8Array(n);
          for (let i = 0; i < n; i++) {
            arr[i] = b64.charCodeAt(i);
          }
          let downloadFile = new File([arr], "pdf" + interviewId + ".pdf", {
            type: "application/pdf",
          });
          console.log(downloadFile);
          //创建下载路径
          let url = window.URL.createObjectURL(downloadFile);
          //创建a标签
          let a = document.createElement("a");
          a.href = url;
          a.target = "_Blank";
          document.body.appendChild(a);
          a.click();
          //下载完成移除a标签
          document.body.removeChild(a);
          //释放连接
          window.URL.revokeObjectURL(url);
        })
        .catch((error) => {
          console.log(error);
          // this.$Spin.hide();
          this.$Message.error("下载失败，请检查网络设置");
        })
        .finally(() => {
          //  关闭加载
          this.$Spin.hide();

        });
    },
    // 警告提示
    warning(str) {
      this.$Message.warning(str);
    },
    // 下载录音文件
    async DownloadRecording(index) {
      // console.log(index);
      let interviewId = this.data1[index]["id"];
      // console.log("面试id" + this.data1[index]["id"]);

      // const res = await fetch(
      //   "/api/AdminInterface/DownloadRecording/" + interviewId
      // ).then((response) => response.json());
      // ------------

      //显示加载动画
      this.$Spin.show();
      await fetch("/api/AdminInterface/DownloadRecording/" + interviewId)
        .then((res) => {
          if (res.status === 200) {
            return res.json();
          }
          throw new Error("Error");
        })
        .then((json) => {
          let b64 = atob(json["key"]);
          if (b64.length == 0) {
            // 如果没有文件
            this.warning("此面试没有录音文件");
          } else {
            // console.log(b64);
            let n = b64.length;
            let arr = new Uint8Array(n);
            for (let i = 0; i < n; i++) {
              arr[i] = b64.charCodeAt(i);
            }
            let downloadFile = new File([arr], "wav" + interviewId + ".wav", {
              type: "audio/wav",
            });
            console.log(downloadFile);
            //创建下载路径
            let url = window.URL.createObjectURL(downloadFile);
            //创建a标签
            let a = document.createElement("a");
            a.href = url;
            a.target = "_Blank";
            a.download = "wav" + interviewId + ".wav";
            document.body.appendChild(a);
            a.click();
            //下载完成移除a标签
            document.body.removeChild(a);
            //释放连接
            window.URL.revokeObjectURL(url);
          }
        })
        .catch((error) => {
          console.log(error);
          this.$Spin.hide();
          this.$Message.error("下载失败，请检查网络设置");
        })
        .finally(() => {
          //  隐藏加载动图
          this.$Spin.hide();
        });
    },
    // 导出表格为exsel
    exportData() {
      this.$refs.selection.exportCsv({
        filename: "Adalab面试信息",
      });
    },

    // 排序
    async setsortBy() {
      if (this.sortBy == "Wonderland AI 排序") {
        this.$Spin.show();
        const res = await fetch("/api/AdminInterface/TimeSortBy").then(
          (response) => response.json()
        );

        this.data1 = res;

        // console.log(this.data1);

        for (let index = 0; index < this.data1.length; index++) {
          this.data1[index]["InterviewTime"] = this.getTaskTime(
            this.data1[index]["InterviewTime"]
          );

          if (this.data1[index]["Status"] == "null") {
            this.$set(this.data1[index], "cellClassName", {
              Status: "demo-table-info-cell-name",
            });
            this.data1[index]["Status"] = "未开始.";
          } else if (this.data1[index]["Status"] == "true") {
            this.$set(this.data1[index], "cellClassName", {
              Status: "demo-table-info-cell-age",
            });
            this.data1[index]["Status"] = "进行中√";
          } else if (this.data1[index]["Status"] == "false") {
            this.$set(this.data1[index], "cellClassName", {
              Status: "demo-table-info-cell-address",
            });
            this.data1[index]["Status"] = "已结束×";
          }
        }
        this.$Spin.hide();
        // console.log(this.data1);
        this.sortBy = "Not Wonderland AI 排序";
      } else {
        this.getInformation();
        this.sortBy = "Wonderland AI 排序";
      }
    },
    // 添加用户
    async handleSubmit(name) {
      // console.log(this.formInline);
      this.$Spin.show();
      await this.$refs[name].validate((valid) => {
        if (valid) {
          const DATA = {
            username: this.formInline.user,
            password: this.formInline.password,
          };

          fetch("api/AdminInterface/addUser", {
            method: "POST",

            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(DATA),
          })
            .then((data) => {
              if (!data.ok) {
                this.$Message.error("添加失败");
                throw Error(data.status);
              }
              this.$Spin.hide();
              return data.json();
            })
            .then((update) => {
              this.$Spin.hide();
              this.$Notice.open({
                title: "成功添加第" + update["id"] + "用户",
                desc:
                  "账户：" +
                  update["username"] +
                  "; 密码：" +
                  update["password"],
                duration: 0,
              });
              this.getUserName();
              this.$Message.success("添加成功!");
            });
        } else {
          this.$Message.error("Fail!");
        }
      });
    },

    // 获取所有的面试信息
    async getInformation() {
      this.$Spin.show();
      const res = await fetch("/api/AdminInterface/getInformation").then(
        (response) => response.json()
      );

      this.data1 = res;

      // console.log(this.data1);

      for (let index = 0; index < this.data1.length; index++) {
        this.data1[index]["InterviewTime"] = this.getTaskTime(
          this.data1[index]["InterviewTime"]
        );

        if (this.data1[index]["Status"] == "null") {
          this.$set(this.data1[index], "cellClassName", {
            Status: "demo-table-info-cell-name",
          });
          this.data1[index]["Status"] = "未开始.";
        } else if (this.data1[index]["Status"] == "true") {
          this.$set(this.data1[index], "cellClassName", {
            Status: "demo-table-info-cell-age",
          });
          this.data1[index]["Status"] = "进行中√";
        } else if (this.data1[index]["Status"] == "false") {
          this.$set(this.data1[index], "cellClassName", {
            Status: "demo-table-info-cell-address",
          });
          this.data1[index]["Status"] = "已结束×";
        }
        // console.log(this.data1);
      }
      this.$Spin.hide();
    },

    // 删除
    async PostDel() {
      const DATA = {
        id: this.selection.ids,
      };

      await fetch("api/AdminInterface/del", {
        method: "POST",

        headers: {
          "Content-Type": "application/json",
        },

        body: JSON.stringify(DATA),
      })
        .then((data) => {
          if (!data.ok) {
            throw Error(data.status);
          }

          return data.json();
        })
        .then((update) => {
          // post的响应体
          this.data1 = update;
          this.getInformation();
          this.$Notice.open({
            title: "adalab通知",
            desc: false
              ? ""
              : "系统检测到您刚刚删除了" + this.selection.length + "条面试信息",
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },

    SelectInformation(selection) {
      // console.log(selection);
      this.selection.length = selection.length;
      this.selection.ids = selection.map((item) => item["id"]);
      // console.log(selection);
      // console.log(this.selection.ids);
    },

    handleSelectAll(status) {
      this.$refs.selection.selectAll(status);
    },

    openInterviewee() {
      this.data.isShowInterviewee = true;
    },

    selectInterviewee(e) {
      this.data.interviewee = e.target.innerText;
      this.deselect();
      this.data.intervieweeMsg = this.data.interviewee;
    },

    openInterviewer() {
      this.data.isShowInterviewer = true;
    },

    selectInterviewer(e) {
      this.data.interviewer = e.target.innerText;
      this.deselect();
      this.data.interviewerMsg = this.data.interviewer;
    },

    deselect() {
      this.data.isShowInterviewee = false;
      this.data.isShowInterviewer = false;
    },

    //Thu Aug 18 20:38:54 CST 2016 时间转换
    getTaskTime(strDate) {
      // console.log(strDate);
      var date = new Date(strDate);
      // console.log(date);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      var minute = date.getMinutes();
      // console.log(h);
      minute = minute < 10 ? "0" + minute : minute;
      var str = y + "-" + m + "-" + d + " " + h + ":" + minute + ":00";
      // console.log(str);
      return str;
    },

    getBase64: (file) =>
      new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          resolve(reader.result.substring(reader.result.indexOf(",") + 1));
        };
        reader.onerror = (error) => {
          console.log("Error: ", error);
          reject(error);
        };
      }),

    async publishTask() {
      if (this.filename != null) {
        var file = document.querySelector('#files > input[type="file"]')
          .files[0];
        this.num = await this.getBase64(file); // prints the base64 string
        const DATA = {
          interviewee: this.data.interviewee,
          interviewer: this.data.interviewer,
          time: this.getTaskTime(this.data.time),
          base64: this.num,
        };

        if (
          this.num != "" &&
          this.data.time != "" &&
          this.data.interviewer != "" &&
          this.data.interviewee != ""
        ) {
          if (this.data.interviewer != this.data.interviewee) {
            //显示点击发布后的加载动图
            this.spinShow = true;
            await fetch("api/AdminInterface/postTask", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify(DATA),
            })
              .then((data) => {
                this.getInformation();
                if (!data.ok) {
                  throw Error(data.status);
                }
                return data.json();
              })
              .then((update) => {
                // this.getInformation();
              })
              .finally(() => {
                //隐藏点击发布后的加载动图
                this.spinShow = false;
              });

            // 发布面试之后更新更新所有面试者页面
            this.$Message.success("发布成功");
            this.data.interviewee = "";
            this.data.interviewer = "";
            this.data.intervieweeMsg = "点击选择";
            this.data.interviewerMsg = "点击选择";
            this.data.time = "";
            this.num = "";
          } else {
            this.$Message.error("面试者与面试官不能为同一个人");
          }
        } else {
          this.$Message.error("您需要填入完整的信息");
        }
      } else {
        this.$Message.error("请先选择文档");
      }
    },

    getUserName() {
      fetch("api/AdminInterface/getUser").then((res) =>
        res.json().then((res) => {
          this.data.user = res;
        })
      );
    },
  },
};
</script>

<style scoped>
#bodyDiv {
  width: 100%;
  height: 70vh;
  display: flex;
  justify-content: center;
  align-items: center;
  zoom: 124%;
}

.modal {
  position: fixed;
  width: 100%;
  height: 100vh;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 2;
}

.modal-cont {
  position: absolute;
  left: 50%;
  top: 4.5%;
  transform: translateX(-50%);
  width: 17.1875rem;
  height: 27.5rem;
  background-color: #ffffff;
  border-radius: 0.3125rem;
  padding: 0.3125rem 0.625rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.close-btn {
  font-size: 1rem;
  float: right;
  color: lightgray;
  position: absolute;
  right: 0.625rem;
  top: 0;
}

.close-btn:hover {
  cursor: pointer;
  color: black;
}

.modal-cont-title {
  width: 17.1875rem;
  padding: 0.625rem 0;
  display: flex;
  justify-content: center;
  border-bottom: 0.0625rem solid #dedede;
}

.userList {
  width: 17.1875rem;
  display: flex;
  flex-direction: column;
  overflow: scroll;
}

.userName {
  width: 100%;
  height: 2.5rem;
  line-height: 2.5rem;
  color: #363636;
  text-decoration: none;
  text-align: center;
}

.userName:hover {
  background-color: #dedede;
}

#adminApp {
  width: 12.5rem;
}

.selectUser {
  width: 4.6875rem;
  height: 4.6875rem;
  border-radius: 3.125rem;
  border: none;
  background-color: #2a82e4;
  color: #ffffff;
}

.selectUser:hover {
  cursor: pointer;
}

#adminSelectUser {
  width: 12.5rem;
  display: flex;
  justify-content: space-between;
  margin-bottom: 1.5625rem;
}

.moduleDescription {
  letter-spacing: 0.2ch;
  margin-bottom: 0.625rem;
}

#selectTime {
  margin-bottom: 1.5625rem;
}

#interviewContent {
  margin-bottom: 1.5625rem;
}

#release {
  width: 100%;
  display: flex;
  justify-content: center;
}

#releaseButton {
  padding: 0.3125rem 1.5625rem;
  background-color: #2a82e4;
  color: #ffffff;
  border-radius: 0.1875rem;
  border: none;
}

#releaseButton:hover {
  cursor: pointer;
}

.Information {
  position: absolute;
  top: 3.125rem;
  left: 0.625rem;
}

.informationBtn {
  margin-bottom: 0.625rem;
}

.xinXiBotton {
  display: flex;
  justify-content: space-between;
}

.xinXiBotton > * > * {
  margin: 10px;
}

#addUserCont {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

#addUser {
  display: flex;
  flex-direction: column;
  align-items: center;
}
/* 加载动画 */
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
.seles_wenDang {
  border-radius: 3px;
  width: 100%;
  color: #ffffff;
  background-color: #2a82e4;
}
</style>
<style>
.ivu-table .demo-table-info-row td {
  background-color: #2db7f5;
  color: #fff;
}
.ivu-table .demo-table-error-row td {
  background-color: #ff6600;
  color: #fff;
}
.ivu-table td.demo-table-info-column {
  background-color: #2db7f5;
  color: #fff;
}
/* 未开始 */
.ivu-table .demo-table-info-cell-name {
  color: black;
  background: #ffeeee; /* fallback for old browsers */
  background: -webkit-linear-gradient(
    to right,
    rgb(255, 238, 238),
    rgb(221, 239, 187)
  ); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(
    to right,
    rgb(255, 238, 238),
    rgb(221, 239, 187)
  ); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
/* 进行中 */
.ivu-table .demo-table-info-cell-age {
  color: black;
  background: #ff9966; /* fallback for old browsers */
  background: -webkit-linear-gradient(
    to right,
    rgb(255, 153, 102),
    rgb(255, 94, 98)
  ); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(
    to right,
    rgb(255, 153, 102),
    rgb(255, 94, 98)
  ); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
/* 面试结束 */
.ivu-table .demo-table-info-cell-address {
  color: black;
  background: #22c1c3; /* fallback for old browsers */
  background: -webkit-linear-gradient(
    to right,
    rgb(34, 193, 195),
    rgb(253, 187, 45)
  ); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(
    to right,
    rgb(34, 193, 195),
    rgb(253, 187, 45)
  ); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
</style>
